import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xiaofanshu_flutter/config/custom_icon.dart';
import 'package:xiaofanshu_flutter/controller/attention_controller.dart';
import 'package:xiaofanshu_flutter/controller/near_notes_controller.dart';
import 'package:xiaofanshu_flutter/controller/recommend_controller.dart';
import 'package:xiaofanshu_flutter/mapper/recommend_tab_mapper.dart';
import 'package:xiaofanshu_flutter/pages/home/index/attention.dart';
import 'package:xiaofanshu_flutter/pages/home/index/near_notes.dart';
import 'package:xiaofanshu_flutter/pages/home/index/recommend.dart';
import 'package:xiaofanshu_flutter/static/custom_color.dart';
import 'package:xiaofanshu_flutter/static/custom_string.dart';
import 'package:xiaofanshu_flutter/utils/toast_util.dart';
import 'package:xiaofanshu_flutter/utils/store_util.dart';
import 'package:xiaofanshu_flutter/utils/guide_service.dart';
import 'package:xiaofanshu_flutter/config/guide_config.dart';
import 'package:xiaofanshu_flutter/controller/home_controller.dart';

class IndexPage extends StatefulWidget {
  const IndexPage({super.key});

  @override
  State<IndexPage> createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage> with TickerProviderStateMixin {
  AttentionController attentionController = Get.find();
  RecommendController recommendController = Get.find();
  NearNotesController nearNotesController = Get.find();
  late TabController _tabController;

  // ========== 新增：引导相关 ==========
  final GlobalKey _recommendTabKey = GlobalKey();
  final GlobalKey _attentionTabKey = GlobalKey();
  final GlobalKey _nearbyTabKey = GlobalKey();
  final GlobalKey _searchKey = GlobalKey();
  
  GuideController? _guideController;
  bool _hasShownGuide = false;
  // ==================================

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this, initialIndex: 1);
    _tabController.addListener(() {
      Get.log('index: ${_tabController.index}');
      if (_tabController.indexIsChanging) {
        return;
      }
      if (_tabController.index == 0) {
        attentionController.onTap();
      } else if (_tabController.index == 1) {
        recommendController.onTap();
      } else if (_tabController.index == 2) {
        nearNotesController.onTap();
      }
    });
    
    // ========== 新增：初始化引导 ==========
    try {
      _guideController = Get.find<GuideController>();
      
      // 监听引导触发器
      ever(_guideController!.shouldShowIndexGuide, (shouldShow) {
        if (shouldShow && mounted) {
          Get.log('📢 收到 IndexPage 引导触发信号');
          _hasShownGuide = false; // 重置标志
          
          // 延迟一下，确保UI完全渲染
          Future.delayed(const Duration(milliseconds: 300), () {
            if (mounted) {
              _showGuideIfNeeded();
            }
          });
          
          _guideController?.resetIndexGuideTrigger();
        }
      });
      
      Get.log('✅ IndexPage 引导监听器已设置');
    } catch (e) {
      _guideController = null;
      Get.log('❌ 找不到 GuideController: $e');
    }
    // ==================================
  }
  
  // ========== 新增：显示引导方法 ==========
  Future<void> _showGuideIfNeeded() async {
    Get.log('🔍 _showGuideIfNeeded 被调用: _guideController=${_guideController != null}, _hasShownGuide=$_hasShownGuide');
    
    if (_guideController == null || _hasShownGuide) {
      Get.log('⏭️ 跳过引导显示: controller=${_guideController != null}, hasShown=$_hasShownGuide');
      return;
    }
    
    // 检查全局引导状态
    bool isGuideCompleted = await GuideService.isGuideCompleted();
    if (isGuideCompleted) {
      Get.log('⏭️ 全局引导已完成，跳过 IndexPage 引导');
      _hasShownGuide = true;
      return;
    }
    
    try {
      if (mounted) {
        _hasShownGuide = true;
        Get.log('🎬 准备显示 IndexPage 引导...');
        
        // 延迟确保 UI 完全渲染
        await Future.delayed(const Duration(milliseconds: 500));
        
        if (!mounted) {
          Get.log('❌ 页面已销毁，取消引导显示');
          return;
        }
        
        // 创建引导步骤
        final steps = GuideConfig.createHomeGuideTargets(
          recommendTabKey: _recommendTabKey,
          attentionTabKey: _attentionTabKey,
          nearbyTabKey: _nearbyTabKey,
          searchKey: _searchKey,
        );
        
        // 显示引导
        GuideService.showGuide(
          context: context,
          steps: steps,
          onFinish: () async {
            Get.log('✅ IndexPage 引导完成');
            await GuideService.setHomeGuideCompleted();
            
            // 注意：列表页引导已被移除，不再作为引导流程的一部分
            // 如果用户手动触发了列表页引导，这里只是标记完成，不再跳转
            Get.log('ℹ️ 列表页引导不在默认流程中');
          },
          onSkip: () async {
            Get.log('⏭️ 用户跳过 IndexPage 引导');
            await GuideService.setGuideCompleted();
            _guideController?.completeAllGuides();
            
            Get.snackbar(
              '已跳过引导',
              '您可以在设置中重新查看新手引导',
              snackPosition: SnackPosition.BOTTOM,
              duration: const Duration(seconds: 2),
            );
          },
        );
        
        Get.log('✅ IndexPage 引导已显示');
      }
    } catch (e) {
      Get.log('❌ IndexPage 引导显示失败: $e');
    }
  }
  // =====================================

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      drawer: Drawer(
        child: Container(
          color: Colors.white,
          child: SafeArea(
            child: Column(
              children: [
                // 菜单列表
                Expanded(
                  child: ListView(
                    padding: const EdgeInsets.symmetric(vertical: 8),
                    children: [
                      _buildMenuItem(
                        icon: Icons.storefront_outlined,
                        title: '故事商城',
                        subtitle: '发现更多精彩内容',
                        iconColor: const Color(0xffff6b6b),
                        iconBgColor: const Color(0xffffe5e5),
                        onTap: () {
                          Navigator.pop(context);
                          ToastUtil.showSimpleToast('故事商城功能开发中，敬请期待');
                        },
                      ),
                    ],
                  ),
                ),
                
                // 底部版本信息
                _buildDrawerFooter(),
              ],
            ),
          ),
        ),
      ),
      appBar: AppBar(
        leading: Builder(
          builder: (BuildContext context) {
            return IconButton(
              icon: const Icon(
                CustomIcon.menu,
                color: Colors.black87,
                size: 30,
              ),
              onPressed: () {
                Scaffold.of(context).openDrawer();
              },
            );
          },
        ),
        leadingWidth: 40,
        centerTitle: true,
        title: TabBar(
          controller: _tabController,
          tabAlignment: TabAlignment.center,
          overlayColor: WidgetStateProperty.all(Colors.transparent),
          enableFeedback: false,
          isScrollable: true,
          indicatorColor: CustomColor.primaryColor,
          labelColor: CustomColor.primaryColor,
          unselectedLabelColor: CustomColor.unselectedColor,
          indicatorSize: TabBarIndicatorSize.label,
          labelStyle: const TextStyle(fontSize: 16),
          onTap: (index) {
            _tabController.animateTo(index);
          },
          // ========== 修改：添加 GlobalKey ==========
          tabs: [
            Tab(key: _attentionTabKey, text: IndexTabName.attention),
            Tab(key: _recommendTabKey, text: IndexTabName.recommend),
            Tab(key: _nearbyTabKey, text: IndexTabName.nearBy),
          ],
          // =========================================
        ),
        // ========== 修改：添加 GlobalKey ==========
        actions: [
          IconButton(
            key: _searchKey, // 添加 key
            icon: const Icon(Icons.search, color: Colors.black87, size: 30),
            onPressed: () {
              Get.toNamed('/search');
            },
          ),
        ],
        // =========================================
        backgroundColor: const Color(0xffffffff),
      ),
      body: TabBarView(
        controller: _tabController,
        children: const [
          AttentionPage(),
          RecommendPage(),
          NearNotesPage(),
        ],
      ),
    );
  }

  // 构建 Drawer 头部
  Widget _buildDrawerHeader() {
    return FutureBuilder<String?>(
      future: readData('nickname'),
      builder: (context, snapshot) {
        String nickname = snapshot.data ?? '游客';
        return Container(
          padding: const EdgeInsets.fromLTRB(16, 24, 16, 16),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
              colors: [
                CustomColor.primaryColor,
                CustomColor.primaryColor.withOpacity(0.8),
              ],
            ),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              FutureBuilder<String?>(
                future: readData('avatarUrl'),
                builder: (context, avatarSnapshot) {
                  return Container(
                    width: 70,
                    height: 70,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      border: Border.all(color: Colors.white, width: 3),
                      image: avatarSnapshot.hasData && avatarSnapshot.data != null
                          ? DecorationImage(
                              image: NetworkImage(avatarSnapshot.data!),
                              fit: BoxFit.cover,
                            )
                          : null,
                      color: Colors.white.withOpacity(0.3),
                    ),
                    child: avatarSnapshot.hasData && avatarSnapshot.data != null
                        ? null
                        : const Icon(
                            Icons.person,
                            size: 40,
                            color: Colors.white,
                          ),
                  );
                },
              ),
              const SizedBox(height: 12),
              Text(
                nickname,
                style: const TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
              const SizedBox(height: 4),
              GestureDetector(
                onTap: () {
                  Navigator.pop(context);
                  Get.toNamed('/mine');
                },
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.2),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: const Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        '查看个人主页',
                        style: TextStyle(
                          fontSize: 13,
                          color: Colors.white,
                        ),
                      ),
                      SizedBox(width: 4),
                      Icon(
                        Icons.arrow_forward_ios,
                        size: 12,
                        color: Colors.white,
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  // 构建菜单项
  Widget _buildMenuItem({
    required IconData icon,
    required String title,
    required String subtitle,
    required Color iconColor,
    required Color iconBgColor,
    required VoidCallback onTap,
  }) {
    return ListTile(
      onTap: onTap,
      contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
      leading: Container(
        width: 48,
        height: 48,
        decoration: BoxDecoration(
          color: iconBgColor,
          borderRadius: BorderRadius.circular(12),
        ),
        child: Icon(
          icon,
          color: iconColor,
          size: 26,
        ),
      ),
      title: Text(
        title,
        style: const TextStyle(
          fontSize: 16,
          fontWeight: FontWeight.w600,
          color: Color(0xff2b2b2b),
        ),
      ),
      subtitle: Text(
        subtitle,
        style: const TextStyle(
          fontSize: 12,
          color: Color(0xff999999),
        ),
      ),
      trailing: const Icon(
        Icons.chevron_right,
        color: Color(0xffcccccc),
        size: 20,
      ),
    );
  }

  // 构建 Drawer 底部
  Widget _buildDrawerFooter() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        border: Border(
          top: BorderSide(
            color: Colors.grey.withOpacity(0.2),
            width: 1,
          ),
        ),
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                Icons.auto_stories,
                size: 16,
                color: CustomColor.primaryColor,
              ),
              const SizedBox(width: 6),
              Text(
                '这里有故事',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                  color: CustomColor.primaryColor,
                ),
              ),
            ],
          ),
          const SizedBox(height: 4),
          const Text(
            'Version 1.0.0',
            style: TextStyle(
              fontSize: 11,
              color: Color(0xff999999),
            ),
          ),
        ],
      ),
    );
  }
}
